import React, { Component, createRef } from 'react'
import {
  Breadcrumb,
  Divider,
  Form,
  Input,
  Button,
  Radio,
  Upload,
  Space,
  Modal,
  message,
} from 'antd'
import styles from './index.module.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import SelectChannel from 'components/SelectChannel'
import { baseURL } from 'utils/request'
import { loadArticle, publishArticle, editArticle } from 'api/article'

export default class Publish extends Component {
  state = {
    fileList: [],
    type: 1,
    isModalVisible: false,
    previewImg: null,
    isEdit: this.props.match.params.id,
  }

  formRef = createRef()

  fileChange = ({ file, fileList }) => {
    this.setState({ fileList })
  }

  coverChange = (e) => {
    const { value } = e.target
    const { fileList } = this.state
    if (fileList.length > value) {
      this.setState({ fileList: fileList.slice(fileList.length - value) })
    }
    this.setState({ type: value })
  }

  onPublish = async (values) => {
    const { fileList, type, isEdit } = this.state
    if (type !== fileList.length) return message.error('请选择相应数量的图片！')
    const data = {
      ...values,
      cover: {
        type: values.type,
        images: fileList,
      },
    }
    try {
      if (isEdit) {
        await editArticle({ ...data, id: isEdit })
        message.success('修改成功')
      } else {
        await publishArticle(data)
        message.success(data.draft ? '存储成功' : '发布成功')
      }
      this.props.history.push('/home/article')
    } catch (err) {
      message.error('发布失败')
    }
  }

  onFinish = (values) => {
    this.onPublish({ ...values, draft: false })
  }

  onPreview = (file) => {
    this.setState({ previewImg: file.response.data.url })
    this.setState({ isModalVisible: true })
  }

  saveDraft = async () => {
    const values = await this.formRef.current.validateFields()
    this.onPublish({ ...values, draft: true })
  }

  async componentDidMount() {
    const { id } = this.props.match.params
    if (id) {
      const { data } = await loadArticle(id)
      this.setState({
        fileList: data.cover.images,
        type: data.cover.type,
      })
      this.formRef.current.setFieldsValue({ ...data, type: data.cover.type })
    }
  }

  render() {
    const { id } = this.props.match.params

    const { fileList, type, isModalVisible, previewImg, initialValues } =
      this.state

    return (
      <div className={styles.publish}>
        <Breadcrumb>
          <Breadcrumb.Item
            onClick={() => {
              this.props.history.push('/home')
            }}
          >
            首页
          </Breadcrumb.Item>
          <Breadcrumb.Item>文章发布</Breadcrumb.Item>
        </Breadcrumb>
        <Divider />

        <Form
          name="basic"
          labelCol={{ span: 3, offset: 1 }}
          wrapperCol={{ span: 10 }}
          initialValues={initialValues}
          onFinish={this.onFinish}
          autoComplete="off"
          ref={this.formRef}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[{ required: true, message: '请输入你的标题!' }]}
          >
            <Input placeholder="请输入你的标题" />
          </Form.Item>

          <Form.Item
            label="频道"
            name="channel_id"
            rules={[{ required: true, message: '请选择你的频道!' }]}
          >
            <SelectChannel />
          </Form.Item>

          <Form.Item initialValue={1} label="封面" name="type">
            <Radio.Group onChange={this.coverChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Upload
              action={`${baseURL}v1_0/upload`}
              name="image"
              listType="picture-card"
              fileList={fileList}
              onChange={this.fileChange}
              maxCount={type}
              onPreview={this.onPreview}
            >
              上传
            </Upload>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[{ required: true, message: '请输入内容!' }]}
          >
            <ReactQuill
              placeholder="请输入文章内容..."
              style={{ width: 602 }}
            />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 4 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                {id ? '修改文章' : '发布文章'}
              </Button>
              <Button onClick={this.saveDraft}>存为草稿</Button>
            </Space>
          </Form.Item>
        </Form>

        <Modal
          visible={isModalVisible}
          footer={null}
          onCancel={() => this.setState({ isModalVisible: false })}
        >
          <img src={previewImg} style={{ width: '100%' }} />
        </Modal>
      </div>
    )
  }
}
